import { config } from '../config/index.js';

/**
 * 生成JWT Payload
 */
export function generateTokenPayload(user) {
  return {
    userId: user.id,
    username: user.username,
    email: user.email,
    role: user.role,
  };
}

/**
 * 解析过期时间字符串 (如 '15m', '7d')
 */
export function parseExpiryTime(timeString) {
  const units = {
    s: 1,
    m: 60,
    h: 3600,
    d: 86400,
    w: 604800,
  };
  
  const match = timeString.match(/^(\d+)([smhdw])$/);
  if (!match) {
    throw new Error(`Invalid time format: ${timeString}`);
  }
  
  const value = parseInt(match[1]);
  const unit = match[2];
  
  return value * units[unit];
}

/**
 * 计算过期时间戳
 */
export function calculateExpiryTimestamp(expiryString) {
  const seconds = parseExpiryTime(expiryString);
  return new Date(Date.now() + seconds * 1000);
}

/**
 * 验证JWT配置
 */
export function validateJwtConfig() {
  if (!config.jwt.secret) {
    throw new Error('JWT_SECRET is not configured');
  }
  
  if (config.env === 'production' && config.jwt.secret.length < 32) {
    throw new Error('JWT_SECRET must be at least 32 characters in production');
  }
}


